package com.jy.rhin.domain.document.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author dhl
 * @date 2022/6/2
 * @Description
 */
@Slf4j
@Component
public class DocumentFilterFactory implements ApplicationContextAware {

    /**
     * 不同类型的过滤器集合
     */
    Map<DocumentFilterDescEnum.FilterType, List<DocumentFilter>> filterByTypeMap = new EnumMap<>(DocumentFilterDescEnum.FilterType.class);

    public List<DocumentFilter> getFilterList(DocumentFilterDescEnum.FilterType filterType) {
        return filterByTypeMap.get(filterType);
    }

    /**
     * 启动加载文档过滤器实现类并封装
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, DocumentFilter> documentFilterMap = applicationContext.getBeansOfType(DocumentFilter.class);
        documentFilterMap
                .values()
                .forEach(documentFilter -> {
                    List<DocumentFilterDescEnum.FilterType> filterList = documentFilter.filterDesc().getFilterType();
                    if (!CollectionUtils.isEmpty(filterList)) {
                        for (DocumentFilterDescEnum.FilterType filterType : filterList) {
                            List<DocumentFilter> list = filterByTypeMap.get(filterType);
                            if (Objects.isNull(list)) {
                                list = new ArrayList<>();
                            }
                            list.add(documentFilter);
                            filterByTypeMap.put(filterType, list);
                        }
                    }
                });
        filterByTypeMap
                .values()
                .forEach(documentFilterList ->
                        documentFilterList.sort(Comparator.comparingInt(value -> value.filterDesc().getSort()))
                );
    }
}
